package com.oracle.outsidein.process;

/**
 * Copies standard output and error of subprocesses to given stream pumpers.
 */
public class PumpStreamHandler {

    private final StreamPumper outputPumper;
    private final StreamPumper errorPumper;

    /**
     * Construct a new {@code PumpStreamHandler}.
     *
     * @param outputPumper the output {@code StreamPumper}.
     * @param errorPumper  the error {@code StreamPumper}.
     */
    public PumpStreamHandler(final StreamPumper outputPumper, final StreamPumper errorPumper) {
        this.outputPumper = outputPumper;
        this.errorPumper = errorPumper;
    }

    /**
     * Gets the output {@code StreamPumper}.
     *
     * @return The output pumper.
     */
    public StreamPumper getOutputPumper() {
        return outputPumper;
    }

    /**
     * Gets the error {@code StreamPumper}.
     *
     * @return The error pumper.
     */
    public StreamPumper getErrorPumper() {
        return errorPumper;
    }

    /**
     * Start the pumpers.
     */
    public void start() {
        outputPumper.start();
        errorPumper.start();
    }

    /**
     * Stop pumping the streams.
     */
    public void stop() {
        try {
            outputPumper.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        try {
            errorPumper.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
